<template>
  <div class="details">
    <div class="contenTop" ref="contenTop">
      <div class="details-header">
        <van-nav-bar title="文章详情" left-arrow @click-left="$router.back()" />
      </div>

      <div class="details-top">
        <div class="top-title">
          <!-- 文章标题 -->
          <h3>{{ title }}</h3>
        </div>
        <van-skeleton title avatar :row="2" :loading="!article._id">
          <div class="top-footer">
            <div class="top-footer-l">
              <van-image round width="50" height="50" :src="article.avatar" />

              <div class="footer-l-text">
                <!-- 作者信息 -->
                <span> 作者：{{ article.author }}</span>
                <em>{{ article.time | conversion }}</em>
              </div>
            </div>
            <div class="top-footer-r">
              <van-icon name="plus" />
              <span>已关注</span>
            </div>
          </div>
        </van-skeleton>
      </div>

      <van-skeleton title avatar :row="5" :loading="!article._id">
        <!-- 文章内容 -->
        <div class="details-main">
          <div class="main-article">
            <span v-html="article.content">
              
            </span>
            <div
              class="main-img"
              :class="{
                none: article.poster_type == 1,
                articlesingleImg: article.poster_type == 2,
                articltwoImg: article.poster_type == 3,
              }"
            >
              <van-image
                width="100"
                height="100"
                v-for="img in article.imageSrc"
                :key="img._id"
                :src="img"
              />

              <!-- <img :src="article.imageSrc" alt="" /> -->
            </div>
          </div>

          <!-- 分割线 -->
          <van-divider
            :hairline="false"
            :style="{ borderColor: '#999', padding: '0 5px' }"
          >
          </van-divider>

          <div class="commentListHead">精彩评论</div>

          <!-- 暂无评论 -->
          <!-- <van-empty v-if="this.comment_count == 0" image="error" description="暂无评论，快来抢沙发" /> -->
          <!-- 评论列表 -->
          <div style="min-height: calc(100vh - 106px)">
            <van-list
              v-model="commentLoading"
              :finished="commentFinished"
              finished-text="没有更多了"
              @load="getCommentList"
            >
              <template #loading>
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  xmlns:xlink="http://www.w3.org/1999/xlink"
                  style="
                    margin: auto;
                    background: rgba(255, 255, 255, 0);
                    display: block;
                  "
                  width="67px"
                  height="67px"
                  viewBox="0 0 100 100"
                  preserveAspectRatio="xMidYMid"
                >
                  <g transform="translate(50 50)">
                    <g transform="scale(0.7)">
                      <g transform="translate(-50 -50)">
                        <g>
                          <animateTransform
                            attributeName="transform"
                            type="rotate"
                            repeatCount="indefinite"
                            values="0 50 50;360 50 50"
                            keyTimes="0;1"
                            dur="0.8064516129032259s"
                          ></animateTransform>
                          <path
                            fill-opacity="1"
                            fill="#84fab0"
                            d="M50 50L50 0A50 50 0 0 1 100 50Z"
                          ></path>
                        </g>
                        <g>
                          <animateTransform
                            attributeName="transform"
                            type="rotate"
                            repeatCount="indefinite"
                            values="0 50 50;360 50 50"
                            keyTimes="0;1"
                            dur="1.0752688172043012s"
                          ></animateTransform>
                          <path
                            fill-opacity="1"
                            fill="#8fd3f4"
                            d="M50 50L50 0A50 50 0 0 1 100 50Z"
                            transform="rotate(90 50 50)"
                          ></path>
                        </g>
                        <g>
                          <animateTransform
                            attributeName="transform"
                            type="rotate"
                            repeatCount="indefinite"
                            values="0 50 50;360 50 50"
                            keyTimes="0;1"
                            dur="1.6129032258064517s"
                          ></animateTransform>
                          <path
                            fill-opacity="1"
                            fill="#84fab0"
                            d="M50 50L50 0A50 50 0 0 1 100 50Z"
                            transform="rotate(180 50 50)"
                          ></path>
                        </g>
                        <g>
                          <animateTransform
                            attributeName="transform"
                            type="rotate"
                            repeatCount="indefinite"
                            values="0 50 50;360 50 50"
                            keyTimes="0;1"
                            dur="3.2258064516129035s"
                          ></animateTransform>
                          <path
                            fill-opacity="1"
                            fill="#8fd3f4"
                            d="M50 50L50 0A50 50 0 0 1 100 50Z"
                            transform="rotate(270 50 50)"
                          ></path>
                        </g>
                      </g>
                    </g>
                  </g>
                </svg>
                加载中...
              </template>
              <div
                class="main-footer"
                v-for="(item, index) in commentList"
                :key="item._id"
              >
                <div class="main-footer-l">
                  <van-image
                    round
                    width="40"
                    height="40"
                    :src="item.info.avatar"
                  />
                </div>
                <div class="main-footer-m">
                  <!-- 评论人的名字 -->
                  <i>{{ item.info.nickname }}</i>
                  <span v-html="item.content"></span>
                  <!-- 评论时间 -->
                  <em>{{ item.create_time | conversion }}</em>
                  <em @click="openReplyFiledPopup(item, index)">
                    {{ item.reply_num == 0 ? "" : item.reply_num }}
                    回复
                  </em>
                </div>

                <!-- 评论回复 -->
                <van-popup v-model="popupShow" position="bottom">
                  <div class="post-comment">
                    <van-field
                      v-model="content"
                      rows="4"
                      autosize
                      type="textarea"
                      maxlength="1000"
                      :placeholder="contentPlaceholder"
                      show-word-limit
                      ref="content"
                    />
                    <div style="width: 100%">
                      <van-button
                        size="large"
                        type="primary"
                        @click="addComment"
                        >发布</van-button
                      >
                    </div>
                  </div>
                </van-popup>
                <!-- /评论回复 -->

                <!-- 回复列表 -->
                <van-popup
                  v-model="replyPopupShow"
                  position="bottom"
                  style="height: 100%"
                  z-index="99"
                  round
                >
                  <replyCompontent
                    @close="replyPopupShow = false"
                    @toggleCommentLike="toggleCommentLike"
                    :article_id="article_id"
                    :active_reply_index="active_reply_index"
                    :replayItemInfo="commentList[active_reply_index]"
                  ></replyCompontent>
                  <div class="article-bottom">
                    <van-button
                      class="comment-btn"
                      type="default"
                      round
                      size="small"
                      @click="
                        (reply_num = 0),
                          openReplyFiledPopup(
                            commentList[active_reply_index],
                            active_reply_index,
                            true
                          )
                      "
                      >写评论</van-button
                    >
                  </div>
                </van-popup>

                <!-- /回复列表 -->

                <!-- 评论点赞 -->
                <div
                  class="main-footer-r"
                  @click="toggleCommentLike(item._id, index, item.is_like)"
                >
                  <van-icon name="good-job" :class="{ liked: item.is_like }" />
                  <span>{{ item.like_count == 0 ? "" : item.like_count }}</span>
                </div>
              </div>
            </van-list>
          </div>
        </div>
      </van-skeleton>
    </div>

    <div class="null"></div>
    <!-- 底部评论栏 -->
    <!-- <van-number-keyboard safe-area-inset-bottom /> -->
    <div class="footer">
      <div class="footer-box">
        <div class="input">
          <van-field
            style="padding: 0 5px"
            v-model="content"
            center
            clearable
            input-align="center"
            placeholder="写评论"
          >
            <template #button>
              <van-button
                size="small"
                native-type="button"
                color="rgb(7,193,96)"
                style="border: none"
                @click="addComment"
                >发送</van-button
              >
            </template>
          </van-field>
        </div>

        <!-- 评论图标 -->
        <van-icon
          name="comment-o"
          v-if="!article.comment || article.comment == 0"
        />
        <van-icon name="comment-o" v-else :badge="article.comment" />

        <!-- 是否收藏 -->
        <van-icon
          name="star"
          :color="article.is_fav ? '#f00' : '#777'"
          @click="toggleFav"
        />

        <!-- 是否点赞 -->
        <van-icon
          name="good-job"
          :color="article.is_like ? '#f00' : '#777'"
          @click="toggleLike"
        />
        <!-- 是否分享 -->
        <van-icon name="share" @click="showShare = true" color="#777" />
      </div>
    </div>

    <!-- 分享 -->
    <van-share-sheet
      v-model="showShare"
      title="立即分享给好友"
      :options="options"
      @select="onSelect"
    />

    <!-- 弹出二维码 -->
    <van-popup v-model="qrcodePopup" round position="center" z-index="99">
      <van-image :src="qrcodeurl"> </van-image>
      <button>
        <a :href="qrcodeurl" download>{{ text }}</a>
      </button>
    </van-popup>
  </div>
</template>
 
<script>
import commentListMixin from "./commentList";
import {
  Image as VanImage,
  Lazyload,
  Empty,
  Skeleton,
  Divider,
  Popup,
  ShareSheet,
} from "vant";
import { mapState } from "vuex";
import { getArticleDetail } from "@/api/home";
import { addComment } from "@/api/api";
import "@/common/github-markdown.css";
import replyCompontent from "./replyCompontent.vue";
// 生成二维码的插件
import QRCode from "qrcode";

// 截图的插件
import html2canvas from "html2canvas";

// 收藏
import methods from "./articleMethods";
export default {
  components: {
    [VanImage.name]: VanImage,
    [Lazyload.name]: Lazyload,
    [Skeleton.name]: Skeleton,
    [Divider.name]: Divider,
    [Popup.name]: Popup,
    [replyCompontent.name]: replyCompontent,
    [Empty.name]: Empty,
    [ShareSheet.name]: ShareSheet,
  },
  mixins: [commentListMixin],
  data() {
    return {
      popupShow: false,
      contentPlaceholder: "友善是交流的起点",
      articleContentTop: 0, //  分割线之前的的内容高度
      content: "",
      article: [], //文章详情信息
      article_id: "",
      title: "", //标题
      comment_type: 0,
      reply_comment_id: "", //  回复的评论的 ID
      active_reply_index: 0, //当前回复的评论index
      replyPopupShow: false, //回复列表,
      showShare: false, //分享事件
      options: [
        { name: "微信", icon: "wechat" },
        { name: "QQ", icon: "qq" },
        { name: "微博", icon: "weibo" },
        { name: "复制链接", icon: "link" },
        { name: "分享海报", icon: "poster" },
        { name: "二维码", icon: "qrcode" },
      ],
      qrcodePopup: false, //二维码弹出层
      qrcodeurl: "", //二维码图片
      text: "",
    };
  },
  created() {
    let { id, title } = this.$route.query; //$route当前路由对象里的相关信息
    this.article_id = id;
    this.title = title;
    this.getArticleDetail();
  },
  computed: {
    ...mapState(["uid", "userInfo"]),
  },

  methods: {
    // 复制链接
    copy(params) {
      let input = document.createElement("input");
      input.value = params;
      // input.type = 'hidden'
      document.body.appendChild(input);
      input.select();
      document.execCommand("Copy"); // 执行复制
      document.body.removeChild(input);
    },
    // 分享到微博
    shareTSina() {
      let img = this.article.imageSrc[0];
      let title = this.article.title;

      console.log(img);

      let url = window.location.href;
      window.open(
        "http://service.weibo.com/share/share.php?pic=" +
          encodeURIComponent(img) +
          "&title=" +
          title +
          "&url=" +
          url
      );
    },
    // 分享到QQ
    shareQQ() {
      let img = this.article.imageSrc[0];
      let title = this.article.title;

      console.log(img);

      let url = window.location.href;
      window.open(
        "http://connect.qq.com/widget/shareqq/index.html?pic=" +
          encodeURIComponent(img) +
          "&title=" +
          title +
          "&url=" +
          url
      );
    },
    // 分享到微信
    shareWechat() {
      this.text = "保存图片，分享到微信";
      // With promises
      let url = window.location.href;
      QRCode.toDataURL(url)
        .then((url) => {
          console.log(url);
          this.qrcodeurl = url;
          this.qrcodePopup = true;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 保存二维码
    qrcode() {
      // With promises
      this.text = "保存二维码";
      let url = window.location.href;
      QRCode.toDataURL(url)
        .then((url) => {
          console.log(url);
          this.qrcodeurl = url;
          this.qrcodePopup = true;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 点击分享事件
    onSelect({ name }) {
      console.log(name);
      switch (name) {
        case "复制链接":
          console.log(window.location.href);
          this.$toast("复制成功");
          this.copy(window.location.href);
          break;
        case "微博":
          this.shareTSina();
          break;
        case "QQ":
          this.shareQQ();
          break;
        case "微信":
          this.shareWechat();
          break;
        case "二维码":
          this.qrcode();
          break;
        case "分享海报":
          let contenTop = this.$refs.contenTop;
          if (contenTop) {
            html2canvas(contenTop, {
              allowTaint: true,
            })
              .then((canvas) => {
                console.log(canvas);
var cxt=canvas.getContext('2d');
                    let img = new Image();
                    img.src = require('@/assets/1.png');
                    img.onload = function(){
                   cxt.drawImage(img,10,10);  

                    let res = canvas.toDataURL(); //  画布导出图片

console.log(res) 

                    }
 
              })
              .catch((err) => {
                console.log(err);
              });
          }

          break;
      }
      this.showShare = false;
    },

    // 点击回复评论
    openReplyFiledPopup(item, index, is_child) {
      if (!this.checkLogin()) return;
      let {
        reply_num,
        info: { nickname },
        _id: reply_comment_id,
      } = item;
      this.active_reply_index = index;
      if (reply_num == 0 || is_child) {
        //  没人回复
        this.popupShow = true;
        this.comment_type = 1;
        this.contentPlaceholder = "回复:" + nickname;
        this.reply_comment_id = reply_comment_id;

        this.$nextTick(function () {
          // 自动获取焦点没法用
          // this.$refs.content.focus();
        });
      } else {
        //  后续再说

        this.replyPopupShow = true;
      }
    },
    // 收藏
    ...methods,
    getArticleDetail() {
      let { article_id, uid: user_id } = this;
      getArticleDetail({
        user_id,
        article_id,
      }).then((res) => {
        console.log(res);
        if (res.code == 0) {
          this.article = res.data;
          this.$nextTick(function () {
            //  console.log(this.$refs.articleContentTop.offsetHeight)  ;
            // this.articleContentTop = this.$refs.articleContentTop.offsetHeight;
          });
        } else {
          this.$toast(res.msg);
        }
      });
    },
    // 发布评论
    addComment() {
      if (!this.checkLogin()) return
      let {
        uid: user_id,
        article_id,
        content,
        comment_type,
        reply_comment_id,
      } = this;
      console.log(user_id);
      content = content.trim();
      if (content.length == 0) {
        this.$toast("请输入内容");
        return;
      }
      // 调接口
      addComment({
        user_id,
        article_id,
        content,
        comment_type,
        reply_comment_id,
      }).then((res) => {
        this.$toast(res.msg);
        console.log(res);
        if (res.code == 0) {
          this.article.comment++;
          this.content = "";
          if (comment_type == 0) {
            let { avatar, nickname, username } = this.userInfo;

            let commentDate = {
              article_id,
              comment_type: 0,
              content,
              create_time: new Date().getTime(),
              info: {
                avatar,
                nickname,
                username,
              },
              li_like: false,
              like_count: 0,
              reply_comment_id: "", //回复id
              reply_num: 0, //回复数量
              user_id,
              _id: res.data.id,
            };
            this.skip++;
            this.commentList.unshift(commentDate);

            //回复评论
          } else if (comment_type == 1) {
            if (this.replyPopupShow) {
              // 如果是打开状态则是二级的评论
              console.log(111);
              this.$Bus.$emit("listRefresh");
            } else {
              // 如果是关闭装填的话就走这个
              this.commentList[this.active_reply_index].reply_num++;
              let index = this.active_reply_index;
              let item = this.commentList[index];

              this.openReplyFiledPopup(item, index);
            }
          }

          // 组装好了数据 把数据在前端放到数组中 而不是请求接口
          // 可以自己组装数据
        }
      });
    },
  },
  filters: {
    //3.定义一个处理函数，参数value为要处理数据
    conversion: function (value) {
      //调用Date的方法，处理时间戳
      return new Date(value).toLocaleString();
    },
  },
};
//在data中定义show为false  show默认为false  绑定单击事件点击变为true 在事件里面this.color="red"
</script>

<style lang="scss" lang="less" scoped>
.details {
  height: 100%;
  background-color: rgb(245, 247, 249);
}
.details-top {
  padding: 20px;
  padding-bottom: 10px;
  h3 {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  span {
    word-wrap: break-word;
  }
  .top-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .top-footer-l {
      display: flex;
      width: 70%;
      // img {
      //   width: 17%;
      //   height: 17%;
      //   border-radius: 50%;
      //   margin-right: 10px;
      // }
      .footer-l-text {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        width: 80%;
        span {
          display: block;
          margin-bottom: 5px;
          width: 100%;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        em {
          display: block;
          font-style: normal;
          color: #ccc;
          font-size: 14px;
        }
      }
    }
    .top-footer-r {
      border: 1px solid #ccc;
      padding: 5px 10px;
      border-radius: 20px;
      span {
        margin-left: 5px;
      }
    }
  }
}
.details-main {
  padding: 20px;
  position: relative;
  span {
    word-wrap: break-word;
  }

  .main-img {
    margin-top: 30px;
    text-align: center;
    img {
      margin-top: 50px;
      width: 100%;
    }
  }
  .none {
    display: none;
  }
  .articltwoImg {
    display: flex;
    justify-content: space-evenly;
    align-items: center;
  }
  .articlesingleImg {
    text-align: center;
  }
  &:before {
    content: "";
    position: absolute;
    left: 20px;
    top: 0px;
    right: 20px;
    border-top: 1px solid #ccc;
  }
  .main-footer {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    .main-footer-l {
      width: 12%;
      margin-right: 15px;
      img {
        width: 100%;
        border-radius: 50%;
      }
    }
    .main-footer-m {
      flex: 1;
      i {
        font-style: normal;
        color: rgb(29, 113, 224);
        display: block;
      }
      span {
        display: block;
        font-size: 16px;
      }
      em {
        font-style: normal;
        display: block;
        font-size: 12px;
      }
    }
    .main-footer-r {
      width: 10%;
    }
  }
}
.commentListHead {
  font-weight: bold;
  font-size: 24px;
}
.footer {
  width: 100%;
  position: fixed;
  bottom: 0;
}
.footer-box {
  background-color: #fff;
  align-items: center;
  display: flex;
  justify-content: space-between;
  padding: 5px 10px;

  .input {
    padding: 5px 0;
    width: 70%;

    text-align: center;
    .van-cell {
      border: 1px solid #ccc;
      border-radius: 30px;
      padding: 0;
    }
  }
}
.article-bottom {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: space-around;
  align-items: center;
  box-sizing: border-box;
  height: 44px;
  border-top: 1px solid #d8d8d8;
  background-color: #fff;
  .comment-btn {
    width: 141px;
    height: 23px;
    border: 1px solid #eeeeee;
    font-size: 15px;
    line-height: 23px;
    color: #a7a7a7;
  }
  .van-icon {
    font-size: 20px;
    .van-info {
      font-size: 11px;
      background-color: #e22829;
    }
  }
}
.null {
  width: 100%;
  height: 20px;
}

.liked {
  color: red;
}
::v-deep .van-divider {
  margin-top: 20px;
}
::v-deep .van-button--primary {
  border: none;
}
::v-deep .van-popup--center {
  text-align: center;
  a {
    color: black;
  }
}
</style>